using System;
using System.IO;
using System.Windows.Forms;
using Microsoft.TeamFoundation.WorkItemTracking.Client;
using TXLooker.WorkItemExtention.Core;
using TXLooker.WorkItemExtention.Properties;
using WorkItemExtentionGlobal=TXLooker.WorkItemExtention.Core.WorkItemExtentionGlobal;

namespace TXLooker.WorkItemExtention.UI.QueryManager
{
    public partial class SaveAsQueryForm : Form
    {
        private IQueryManagerProcessor m_queryManagerProcessor;
        private SaveType m_saveType;
        private bool m_bSave;
        private string m_queryString;
        private string m_queryName;
        private StoredQuery m_storedQuery;

        private SaveAsQueryForm()
        {
            InitializeComponent();
        }

        public SaveAsQueryForm(IQueryManagerProcessor queryManagerProcessor, string queryString, string queryName) : this()
        {
            this.QueryManagerProcessor = queryManagerProcessor;
            this.QueryString = queryString;
            this.m_saveType = SaveType.None;
            this.m_queryName = queryName;
        }

        private string QueryString
        {
            get { return this.m_queryString; }
            set { this.m_queryString = value; }
        }

        private IQueryManagerProcessor QueryManagerProcessor
        {
            get { return this.m_queryManagerProcessor; }
            set
            {
                if (object.ReferenceEquals(null, value))
                    throw new NullReferenceException();
                this.m_queryManagerProcessor = value;
            }
        }

        private void EnableFile(bool bEnable)
        {
            this.m_tbFilePath.Enabled = bEnable;
            this.m_btnBrowse.Enabled = bEnable;
            this.m_lFileProject.Enabled = bEnable;
            this.m_cbFileProject.Enabled = bEnable;
            this.m_lLocation.Enabled = bEnable;
        }

        private void EnableMyQueries(bool bEnable)
        {
            this.m_cbMyQueryProject.Enabled = bEnable;
            this.m_lMyQueryProject.Enabled = bEnable;
        }

        private void EnableTeamQueries(bool bEnable)
        {
            this.m_cbTeamQueryProject.Enabled = bEnable;
            this.m_lTeamQueryProject.Enabled = bEnable;
        }

        private void OnLoad(object sender, EventArgs e)
        {
            this.m_tbServer.Text = WorkItemExtentionGlobal.GetServer(this.QueryManagerProcessor.SelectedObject).Host;
            this.m_tbServer.Enabled = false;
            this.m_tbQueryName.Text = this.m_queryName;
            this.m_cbTeamQueryProject.DataSource = this.QueryManagerProcessor.Store.Projects;
            this.m_cbTeamQueryProject.DisplayMember = "Name";
            this.m_cbMyQueryProject.DataSource = this.QueryManagerProcessor.Store.Projects;
            this.m_cbMyQueryProject.DisplayMember = "Name";
            this.m_cbFileProject.DataSource = this.QueryManagerProcessor.Store.Projects;
            this.m_cbFileProject.DisplayMember = "Name";
            this.m_rbTeamQuery.Checked = true;

            this.m_cbTeamQueryProject.SelectedItem = WorkItemExtentionGlobal.GetProject(this.QueryManagerProcessor.SelectedObject);
            this.m_cbMyQueryProject.SelectedItem = WorkItemExtentionGlobal.GetProject(this.QueryManagerProcessor.SelectedObject);
            this.m_cbFileProject.SelectedItem = WorkItemExtentionGlobal.GetProject(this.QueryManagerProcessor.SelectedObject);
        }

        private void OnTemQueryChackedChange(object sender, EventArgs e)
        {
            if (this.m_rbTeamQuery.Checked)
            {
                this.EnableTeamQueries(true);
                this.EnableMyQueries(false);
                this.EnableFile(false);
                this.m_saveType = SaveType.TeamQuery;
            }
        }

        private void OnMyQueryChackedChange(object sender, EventArgs e)
        {
            if (this.m_rbMyQuery.Checked)
            {
                this.EnableTeamQueries(false);
                this.EnableMyQueries(true);
                this.EnableFile(false);
                this.m_saveType = SaveType.MyQuery;
            }
        }

        private void OnFileChackedChange(object sender, EventArgs e)
        {
            if (this.m_rbFile.Checked)
            {
                this.EnableTeamQueries(false);
                this.EnableMyQueries(false);
                this.EnableFile(true);
                this.m_saveType = SaveType.File;
            }
        }

        public bool Save
        {
            get { return this.m_bSave; }
            protected set { this.m_bSave = value; }
        }

        private void m_btnSave_Click(object sender, EventArgs e)
        {
            switch (this.m_saveType)
            { 
                case SaveType.File:
                    m_bSave = this.SaveFile();
                    break;
                case SaveType.MyQuery:
                    m_bSave = this.SaveMyQuery();
                    break;
                case SaveType.TeamQuery:
                    m_bSave = this.SaveTeamQuery();
                    break;
            }

            if (!m_bSave)
                return;
            SetQueryFullName();
            this.Close();
        }

        private void SetQueryFullName()
        {
            switch (this.m_saveType)
            {
                case SaveType.MyQuery:
                    this.FullQueryName = string.Format(Resources.STRING_TABPAGE_MY_QUERIES_NAME, (this.m_cbMyQueryProject.SelectedItem as Project).Name, this.m_tbQueryName.Text);
                    break;
                case SaveType.TeamQuery:
                    this.FullQueryName = string.Format(Resources.STRING_TABPAGE_TEAM_QUERIES_NAME, (this.m_cbTeamQueryProject.SelectedItem as Project).Name, this.m_tbQueryName.Text);
                    break;
                case SaveType.File:
                    break;
                default:
                    throw new NotImplementedException();
                
            }
        }

        public WIObject WIObject
        {
            get { return this.QueryManagerProcessor.SelectedObject; }        
        }

        private bool SaveTeamQuery()
        {
            Project project = this.m_cbTeamQueryProject.SelectedItem as Project;
            StoredQuery query = new StoredQuery(QueryScope.Public, this.m_tbQueryName.Text, this.QueryString, string.Empty);
            try
            {
                project.StoredQueries.Add(query);
                MessageBox.Show(Properties.Resources.QUERY_ADD_SUCCESSFULL, Resources.APPLICATION_NAME, MessageBoxButtons.OK, MessageBoxIcon.Information);
                this.Query = query;
                return true;
            }
            catch (System.UnauthorizedAccessException ex)
            {
                MessageBox.Show(ex.Message, Resources.APPLICATION_NAME, MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }
            catch (Exception)
            {
                MessageBox.Show(this,Resources.WRONG_FIELD_DEFINITIONS, Resources.APPLICATION_NAME, MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }
        }


        private bool SaveMyQuery()
        {
            try
            {
                StoredQuery query = new StoredQuery(QueryScope.Private, this.m_tbQueryName.Text, this.QueryString, string.Empty);
                Project project = this.m_cbMyQueryProject.SelectedItem as Project;

                try
                {
                    project.StoredQueries.Add(query);
                    MessageBox.Show(Properties.Resources.QUERY_ADD_SUCCESSFULL, Resources.APPLICATION_NAME, MessageBoxButtons.OK, MessageBoxIcon.Information);
                    this.Query = query;
                    return true;
                }
                catch (System.UnauthorizedAccessException ex)
                {
                    MessageBox.Show(ex.Message, Resources.APPLICATION_NAME, MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return false;
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, Resources.APPLICATION_NAME, MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return false;
                }
            }
            catch (Exception)
            {
                MessageBox.Show(this, Resources.WRONG_FIELD_DEFINITIONS, Resources.APPLICATION_NAME, MessageBoxButtons.OK, MessageBoxIcon.Stop);
                return false;
            }
        }

        private bool SaveFile()
        {
            try
            {
                using (StreamWriter SW = new StreamWriter(this.m_tbFilePath.Text))
                {
                    string saveString = string.Format(Resources.STRING_SAVE_WORKITEM_IN_FILE, WorkItemExtentionGlobal.GetServer(QueryManagerProcessor.SelectedObject).Host, (this.m_cbFileProject.SelectedItem as Project).Name, this.QueryString.Replace(ConstantOperators.NotEqual, ConstantOperators.XmlNotEquals));
                    SW.Write(saveString);
                }
                return true;
            }
            catch(Exception ex)
            {
                MessageBox.Show(this,ex.Message,Resources.APPLICATION_NAME,MessageBoxButtons.OK,MessageBoxIcon.Stop);
                return false;
            }
        }

        private void OnBrowse(object sender, EventArgs e)
        {
            SaveFileDialog dlg = new SaveFileDialog();

            dlg.Filter = "wiq files (*.wiq)|*.wiq"; ;
            dlg.FilterIndex = 2;
            dlg.RestoreDirectory = true;
            dlg.FileName = this.m_tbQueryName.Text;

            dlg.ShowDialog();
            this.m_tbFilePath.Text = dlg.FileName;
        }

        public StoredQuery Query
        {
            get { return this.m_storedQuery; }
            private set { this.m_storedQuery = value; }
        }

        public SaveType SaveType
        {
            get { return this.m_saveType; }
            private set { this.m_saveType = value; }
        }

        private string m_fullQueryName;
        public string FullQueryName
        {
            get { return this.m_fullQueryName; }
            set { this.m_fullQueryName = value; }
        }
    }
}